<?php
namespace App\Http\Controllers\Admin;

use App\Models\Module;
use Illuminate\Http\Request;

/**
 *
 * @author Joker
 *        
 */
class ModuleController extends BaseController
{
    
    public function index()
    {
        if(!$this->user->can('viewContentModule')) abort(405);
        
        $result = Module::orderBy('sort','DESC')->orderBy('created_at','DESC')->paginate(20);
        
        return view('admin.module.list')->with('result',$result);
    }
    
    public function create()
    {
        if(!$this->user->can('editContentModule')) abort(405);
        
        return view('admin.module.add')->with('blademode','add');
    }
    
    public function edit($id)
    {
        if(!$this->user->can('viewContentModule')) abort(405);
        
        $result = Module::find($id);
        return view('admin.module.details')->with('result',$result)->with('blademode','edit');
    }
    
    public function store(Request $req)
    {
        if(!$this->user->can('editContentModule')) 
            return $this->formatJson('error',$this->permerror);
        
        $data = $req->only('name','alias','intro','link','sort','image_url','blademode','id','description','button','action');
        if($data['blademode'] == 'edit' && $data['id'] > 0)
        {
            $module = Module::find($data['id']);
        }
        else 
        {
            $module = new Module();
        }
        $module->name = $data['name'];
        $module->alias = $data['alias'];
        $module->intro = $data['intro'];
        $module->link = $data['link'];
        $module->sort = $data['sort'];
        $module->image_url = $data['image_url'];
        $module->description = $data['description'];
        $module->button = $data['button'];
        $module->action = $data['action'];
        $module->save();
        return redirect()->intended('admin/content/module');
    }
    
    public function destroy($id)
    {
        if(!$this->user->can('deleteContentModule')) 
            return $this->formatJson('error',$this->permerror);
        
        $modules = Module::find($id);
        if(empty($modules))
            return $this->formatJson('error',$this->noResource);
        
        if($modules->delete())
            return $this->formatJson('success','删除['.$modules->name.'] 成功！');
        else
            return $this->formatJson('error','删除失败！');
    }
    
    
}